package com.qeado.content.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.qeado.admin.common.BaseConstData;
import com.qeado.common.UploadFileLocation;
import com.qeado.common.helper.AttributeHelper;
import com.qeado.content.model.NewsPublish;
import com.qeado.content.service.NewsPublishManageService;

@Controller
public class NewsPublishManageController {
	@Autowired
	private NewsPublishManageService newPublishManageService;
	
	@RequestMapping("/newsPublishManage.ac")
	public String newsPublishManage(HttpServletRequest request) {
		AttributeHelper.removeSessionAttribute(request, "T_");
		List<NewsPublish> newsSortList = newPublishManageService.getNewsSortList();
		request.getSession().setAttribute("T_newsSortList", newsSortList);
		return "content/news_publish_search";
	}
	
	@RequestMapping("/newsPublishSearch.ac")
	public String newsPublishSearch(HttpServletRequest request, NewsPublish news) {
		List<NewsPublish> newsList = newPublishManageService.newsPublishSearch(news);
		request.setAttribute("news", news);
		request.setAttribute("newsList", newsList);
		return "content/news_publish_search";
	}
	
	@RequestMapping("/backToNewsSearch.ac")
	public String backToNewsSearch() {
		return "content/news_publish_search";
	}
	
	@RequestMapping("/newNewsPublish.ac")
	public String newNewsPublish() {
		return "content/news_publish_manage";
	}
	
	@RequestMapping("/selectNews.ac")
	public String selectNews(HttpServletRequest request, String id) {
		NewsPublish news = newPublishManageService.searchNewsPublishById(id);
		request.setAttribute("news", news);
		return "content/news_publish_manage";
	}
	
	@RequestMapping("/deleteNews.ac")
	public ModelAndView deleteNews(String id) {
		newPublishManageService.deleteNews(id);
		List<NewsPublish> newsList = newPublishManageService.newsPublishSearch(null);
		return new ModelAndView("content/news_publish_search", "newsList", newsList);
	}
	
	@RequestMapping("/getNewsPhoto.ac")
	public void getNewsPhoto(HttpServletRequest request, HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
		fileName = URLEncoder.encode(fileName,"UTF-8");
	    response.addHeader("Content-Disposition","attachment;filename=" + fileName);
	    OutputStream output = null;
	    FileInputStream fis = null;
	    try {
	        output = response.getOutputStream();
	        File file = new File(UploadFileLocation.BASE_DIR + "\\news\\" + fileName);
	        fis = new FileInputStream(file);
	        byte[] b = new byte[1024];
	        int i = 0;
	        while((i = fis.read(b)) > 0) {
	            output.write(b, 0, i);
	        }
	        output.flush();
	    } catch(Exception e) {
	        e.printStackTrace();
	    } finally {
	        if(fis != null) { 
	        	try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	        }
	        if(output != null) {
	        	try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	        }
	    }
	}
	
	@RequestMapping("/saveNews.ac")
	public String saveNews(HttpServletRequest request, NewsPublish news) {
		news.setCreator(request.getSession().getAttribute(BaseConstData.USER_ID).toString());
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
		MultipartFile file = multipartRequest.getFile("localFile");
		if(!file.isEmpty()) {
			String imgName = getFileNameByTime(file.getOriginalFilename());
			try {
				String path = UploadFileLocation.BASE_DIR + "\\news" ;
				//analyzePath(path);
				if(!"".equals(news.getFileName())) {
					File oldFile = new File(path + "\\" + news.getFileName());
					oldFile.delete();
				}
				File uploadedFile = new File(path + "\\" + imgName);
				int v;         
				BufferedInputStream inputStream = new BufferedInputStream(file.getInputStream());     
				FileOutputStream outputStream = new FileOutputStream(uploadedFile);     
				byte [] bytes = new byte[1024];     
				while((v = inputStream.read(bytes)) > 0){     
				    outputStream.write(bytes, 0, v);     
				}     
				outputStream.close();     
				inputStream.close();	
			} catch (Exception e) {
				e.printStackTrace();
			}
			news.setNewFileName(imgName);
			news.setFileName(imgName);
		}
		String message = newPublishManageService.saveNews(news);
		request.setAttribute("message", message);
		request.setAttribute("news", news);
		return "content/news_publish_manage";
	}
	
	private synchronized String getFileNameByTime(String input){
        int index = input.lastIndexOf(".");
        return System.currentTimeMillis() + input.substring(index);
    }
	
	private synchronized boolean mkdir(String path) {   
        File file = new File(path); 
        if(file.exists()){ 
        	return false; 
        } else { 
        	file.mkdir(); 
        	return true;
        } 			
	}

	private void analyzePath(String path) {
		String[] paths = path.split("/");
		path = paths[0];
		for(int i=1; i<paths.length; i++) {
			path = path + "\\" +paths[i];
			mkdir(path);
			System.out.println(path);
		}
	}

}
